{% extends "base.html" %}

{% block title %}热门视频 - 社交媒体监控{% endblock %}

{% block page_title %}热门视频{% endblock %}

{% block content %}
<div class="row mb-4">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">手动拉取热门视频</h5>
                </div>
            </div>
            <div class="card-body">
                <form id="fetchForm" class="row g-3">
                    <div class="col-md-3">
                        <label for="page" class="form-label">页码</label>
                        <input type="number" class="form-control" id="page" name="page" value="3" min="3">
                    </div>
                    <div class="col-md-3">
                        <label for="page_size" class="form-label">每页数量</label>
                        <input type="number" class="form-control" id="page_size" name="page_size" value="20" min="5"
                               max="100">
                    </div>
                    <div class="col-md-3">
                        <label for="date_window" class="form-label">时间窗口 (小时)</label>
                        <input type="number" class="form-control" id="date_window" name="date_window" value="24" min="1"
                               max="72">
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button type="button" class="btn btn-primary w-100" onclick="fetchHotVideos()">
                            <i class="bi bi-arrow-repeat"></i> 拉取热门视频
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 新增日期查询过滤器 -->
<div class="row mb-3">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">日期筛选</h5>
            </div>
            <div class="card-body">
                <form id="dateFilterForm" class="row g-3">
                    <div class="col-md-4">
                        <label for="start_date" class="form-label">开始日期</label>
                        <input type="date" class="form-control" id="start_date" name="start_date"
                               value="{{ start_date if start_date else '' }}">
                    </div>
                    <div class="col-md-4">
                        <label for="end_date" class="form-label">结束日期</label>
                        <input type="date" class="form-control" id="end_date" name="end_date"
                               value="{{ end_date if end_date else '' }}">
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <div class="btn-group w-100">
                            <button type="button" class="btn btn-primary" onclick="applyDateFilter()">
                                <i class="bi bi-funnel"></i> 应用筛选
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="clearDateFilter()">
                                <i class="bi bi-x-circle"></i> 清除筛选
                            </button>
                        </div>
                    </div>
                </form>
                <div class="row mt-3">
                    <div class="col-md-12">
                        <div class="btn-group">
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setDateFilter('today')">今天</button>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setDateFilter('yesterday')">昨天</button>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setDateFilter('this_week')">本周</button>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setDateFilter('last_week')">上周</button>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="setDateFilter('this_month')">本月</button>
                        </div>
                        {% if start_date or end_date %}
                        <div class="alert alert-info mt-2 py-2">
                            <small>
                                当前筛选:
                                {% if start_date and end_date %}
                                    {{ start_date }} 至 {{ end_date }}
                                {% elif start_date %}
                                    {{ start_date }} 之后
                                {% else %}
                                    {{ end_date }} 之前
                                {% endif %}
                                <a href="?{% for key, value in request.query_params.items() %}{% if key != 'start_date' and key != 'end_date' %}{{ key }}={{ value }}&{% endif %}{% endfor %}" class="ms-2 text-decoration-none">
                                    <i class="bi bi-x-circle"></i> 清除日期筛选
                                </a>
                            </small>
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row mb-3">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">热门视频列表</h5>
                    <div class="d-flex">
                        <!-- 每页显示数量选择 -->
                        <div class="me-2">
                            <select class="form-select form-select-sm" id="per-page-filter" onchange="changePageSize()">
                                {% for option in per_page_options %}
                                <option value="{{ option }}" {% if per_page== option %}selected{% endif %}>每页 {{
                                    option }} 个
                                </option>
                                {% endfor %}
                            </select>
                        </div>

                        <!-- 排序方式选择 -->
                        <div class="me-2">
                            <select class="form-select form-select-sm" id="sort-by-filter" onchange="changeSort()">
                                {% for option in sort_options %}
                                <option value="{{ option.value }}" {% if option.current %}selected{% endif %}>{{
                                    option.label }}
                                </option>
                                {% endfor %}
                            </select>
                        </div>

                        <!-- 排序顺序切换 -->
                        <button class="btn btn-sm btn-outline-secondary" id="sort-order-toggle"
                                onclick="toggleSortOrder()">
                            <i class="bi {% if sort_order == 'asc' %}bi-sort-down-alt{% else %}bi-sort-up-alt{% endif %}"></i>
                            {% if sort_order == 'asc' %}升序{% else %}降序{% endif %}
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <!-- 批量操作工具栏 -->
                <div class="mb-3 d-flex justify-content-between align-items-center">
                    <div>
                        <button id="selectAllBtn" class="btn btn-outline-primary btn-sm" onclick="toggleSelectAll()">
                            <i class="bi bi-check-all"></i> 全选
                        </button>
                        <button id="unselectAllBtn" class="btn btn-outline-secondary btn-sm d-none"
                                onclick="toggleSelectAll()">
                            <i class="bi bi-x-lg"></i> 取消全选
                        </button>
                        <span id="selectedCount" class="ms-2 badge bg-primary d-none">已选择: 0</span>
                    </div>
                    <div id="batchActions" class="d-none">
                        <button class="btn btn-success btn-sm" onclick="batchDownload()">
                            <i class="bi bi-download"></i> 批量下载
                        </button>
                        <button class="btn btn-danger btn-sm" onclick="batchDelete()">
                            <i class="bi bi-trash"></i> 批量删除
                        </button>
                    </div>
                </div>

                {% if videos %}
                <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-4 g-4">
                    {% for video in videos %}
                    <div class="col">
                        <div class="card h-100 {% if video.is_selected %}border-primary{% endif %} {% if video.download_status == 'downloaded' %}border-success{% endif %}"
                             id="video-card-{{ video.id }}">
                            <div class="position-relative">
                                <img src="{{ video.cover_url }}" class="card-img-top" alt="{{ video.title }}"
                                     style="height: 200px; object-fit: cover;">
                                <div class="position-absolute top-0 start-0 m-2 form-check">
                                    <input class="form-check-input" type="checkbox" id="select-{{ video.id }}"
                                           {% if video.is_selected %}checked{% endif %}
                                           onchange="toggleSelect({{ video.id }})">
                                </div>
                                {% if video.duration %}
                                <span class="position-absolute bottom-0 end-0 badge bg-dark m-2">{{ video.duration }}</span>
                                {% endif %}
                                <span class="position-absolute top-0 end-0 badge bg-danger m-2">Rank #{{ video.rank }}</span>
                                {% if video.download_status == 'downloaded' %}
                                <span class="position-absolute top-0 end-0 badge bg-success m-5">
                                    <i class="bi bi-check-circle-fill"></i> 已下载
                                </span>
                                {% endif %}
                            </div>
                            <div class="card-body">
                                <h6 class="card-title" style="height: auto; overflow: hidden;">{{ video.title }}</h6>
                                <div class="d-flex align-items-center mb-2">
                                    <img src="{{ video.avatar_url }}" class="rounded-circle me-2"
                                         alt="{{ video.author }}" style="width: 24px; height: 24px;">
                                    <small class="text-muted">{{ video.author }}</small>
                                </div>
                                <div class="mb-2">
                                    <small class="text-muted">
                                        <i class="bi bi-eye">播放次数:</i>
                                        <span style="color: red">{{ video.play_count | default(0) | int | format_number }}</span>
                                        <i class="bi bi-heart ms-2">点赞次数:</i>
                                        <span style="color: red">{{ video.like_count | default(0) | int | format_number }}</span>
                                    </small>
                                </div>
                                <div class="mb-2">
                                    <small class="text-muted">发布时间: {{ video.publish_time }}</small>
                                </div>
                            </div>
                            <div class="card-footer">
                                <div class="d-flex justify-content-between align-items-center">
                                    {% if video.download_status == 'downloaded' %}
                                    <a href="/hot-videos/{{ video.id }}/play" class="btn btn-sm btn-success">
                                        <i class="bi bi-play-fill"></i> 播放
                                    </a>
                                    {% elif video.download_status == 'downloading' %}
                                    <button class="btn btn-sm btn-warning" disabled>
                                        <i class="bi bi-download"></i> 下载中...
                                    </button>
                                    {% else %}
                                    <div class="btn-group">
                                        <button class="btn btn-sm btn-primary" onclick="downloadVideo({{ video.id }})">
                                            <i class="bi bi-download"></i> 下载
                                        </button>
                                        <button class="btn btn-sm btn-outline-primary"
                                                onclick="getManualDownloadLinks({{ video.id }})">
                                            <i class="bi bi-link-45deg"></i> 手动下载
                                        </button>
                                    </div>
                                    {% endif %}

                                    <div class="btn-group">
                                        <a class="btn btn-sm btn-outline-secondary"
                                           href="https://www.douyin.com/discover?modal_id={{ video.video_id }}"
                                           target="_blank">
                                            <i class="bi bi-link-45deg"></i> 预览视频
                                        </a>
                                        <button class="btn btn-sm btn-outline-danger"
                                                onclick="deleteVideo({{ video.id }})">
                                            <i class="bi bi-trash">删除</i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>

                <!-- 分页控件 -->
                {% if pagination.pages > 1 %}
                <nav class="mt-4">
                    <ul class="pagination justify-content-center">
                        <li class="page-item {% if pagination.page == 1 %}disabled{% endif %}">
                            <a class="page-link"
                               href="?page=1&per_page={{ per_page }}&platform={{ platform }}&sort_by={{ sort_by }}&sort_order={{ sort_order }}{% if category %}&category={{ category }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">首页</a>
                        </li>
                        <li class="page-item {% if pagination.page == 1 %}disabled{% endif %}">
                            <a class="page-link"
                               href="?page={{ pagination.page - 1 }}&per_page={{ per_page }}&platform={{ platform }}&sort_by={{ sort_by }}&sort_order={{ sort_order }}{% if category %}&category={{ category }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">上一页</a>
                        </li>

                        {% for p in range(pagination.page - 2, pagination.page + 3) %}
                        {% if p > 0 and p <= pagination.pages %}
                        <li class="page-item {% if p == pagination.page %}active{% endif %}">
                            <a class="page-link"
                               href="?page={{ p }}&per_page={{ per_page }}&platform={{ platform }}&sort_by={{ sort_by }}&sort_order={{ sort_order }}{% if category %}&category={{ category }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">{{
                                p }}</a>
                        </li>
                        {% endif %}
                        {% endfor %}

                        <li class="page-item {% if pagination.page >= pagination.pages %}disabled{% endif %}">
                            <a class="page-link"
                               href="?page={{ pagination.page + 1 }}&per_page={{ per_page }}&platform={{ platform }}&sort_by={{ sort_by }}&sort_order={{ sort_order }}{% if category %}&category={{ category }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">下一页</a>
                        </li>
                        <li class="page-item {% if pagination.page >= pagination.pages %}disabled{% endif %}">
                            <a class="page-link"
                               href="?page={{ pagination.pages }}&per_page={{ per_page }}&platform={{ platform }}&sort_by={{ sort_by }}&sort_order={{ sort_order }}{% if category %}&category={{ category }}{% endif %}{% if start_date %}&start_date={{ start_date }}{% endif %}{% if end_date %}&end_date={{ end_date }}{% endif %}">末页</a>
                        </li>
                    </ul>
                </nav>
                <div class="text-center">
                    <small class="text-muted">共 {{ pagination.total }} 条记录，当前第 {{ pagination.page }}/{{ pagination.pages }} 页</small>
                </div>
                {% endif %}

                {% else %}
                <div class="alert alert-info">
                    没有找到热门视频。点击上方"拉取热门视频"按钮获取最新热门视频。
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 进度弹窗 -->
<div class="modal fade" id="progressModal" tabindex="-1" aria-hidden="true" data-bs-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">操作进度</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="progressMessages" class="mb-3" style="max-height: 300px; overflow-y: auto;"></div>
                <div class="progress">
                    <div id="progressBar" class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="0"
                         aria-valuemin="0" aria-valuemax="100">0%
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 手动下载弹窗 -->
<div class="modal fade" id="manualDownloadModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">手动下载链接</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>请使用以下链接下载视频：</p>
                <div id="downloadLinksContainer">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block scripts %}
<script>
    // WebSocket连接
    let ws;
    let progressModal;
    let manualDownloadModal;
    let clientId;
    let allSelected = false;
    let selectedVideos = new Set();

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', function () {
        progressModal = new bootstrap.Modal(document.getElementById('progressModal'));
        manualDownloadModal = new bootstrap.Modal(document.getElementById('manualDownloadModal'));

        // 初始化已选中的视频
        document.querySelectorAll('.form-check-input:checked').forEach(checkbox => {
            const videoId = parseInt(checkbox.id.replace('select-', ''));
            selectedVideos.add(videoId);
        });

        updateSelectedUI();
    });

    // 建立WebSocket连接
    function connectWebSocket(client_id) {
        clientId = client_id;

        // 关闭之前的连接
        if (ws) {
            ws.close();
        }

        // 建立新连接
        ws = new WebSocket(`ws://${window.location.host}/ws/${client_id}`);

        ws.onopen = function () {
            console.log('WebSocket连接已建立');
            addProgressMessage('info', '连接已建立，等待操作完成...');
        };

        ws.onmessage = function (event) {
            const data = JSON.parse(event.data);
            console.log('收到消息', data);

            // 处理进度消息
            if (data.type) {
                handleProgressMessage(data);
            }
        };

        ws.onclose = function () {
            console.log('WebSocket连接已关闭');
        };

        ws.onerror = function (error) {
            console.error('WebSocket错误:', error);
            addProgressMessage('error', '连接错误，请刷新页面重试');
        };
    }

    // 处理进度消息
    function handleProgressMessage(data) {
        switch (data.type) {
            case 'start':
                addProgressMessage('info', data.message);
                updateProgressBar(0);
                break;
            case 'processing':
                addProgressMessage('info', data.message);
                if (data.current && data.total) {
                    const percent = Math.round((data.current / data.total) * 100);
                    updateProgressBar(percent);
                }
                break;
            case 'downloading':
                addProgressMessage('info', data.message);
                break;
            case 'success':
                addProgressMessage('success', data.message);
                if (data.file_path) {
                    addProgressMessage('info', `文件已保存到: ${data.file_path}`);
                }
                break;
            case 'error':
                addProgressMessage('error', data.message);
                break;
            case 'complete':
                addProgressMessage('success', data.message);
                updateProgressBar(100);
                // 操作完成后刷新页面
                setTimeout(function () {
                    location.reload();
                }, 2000);
                break;
            default:
                addProgressMessage('info', data.message);
        }
    }

    // 添加进度消息
    function addProgressMessage(type, message) {
        const messagesContainer = document.getElementById('progressMessages');
        const messageDiv = document.createElement('div');
        messageDiv.className = `alert alert-${messageTypeToClass(type)} py-1 mb-2`;
        messageDiv.innerHTML = message;
        messagesContainer.appendChild(messageDiv);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    // 消息类型转换为Bootstrap样式类
    function messageTypeToClass(type) {
        switch (type) {
            case 'success':
                return 'success';
            case 'error':
                return 'danger';
            case 'warning':
                return 'warning';
            case 'info':
            default:
                return 'info';
        }
    }

    // 更新进度条
    function updateProgressBar(percent) {
        const progressBar = document.getElementById('progressBar');
        progressBar.style.width = `${percent}%`;
        progressBar.setAttribute('aria-valuenow', percent);
        progressBar.textContent = `${percent}%`;
    }

    // 拉取热门视频
    async function fetchHotVideos() {
        try {
            // 收集表单数据
            const page = document.getElementById('page').value;
            const page_size = document.getElementById('page_size').value;
            const date_window = document.getElementById('date_window').value;

            // 显示进度弹窗
            document.getElementById('progressMessages').innerHTML = '';
            updateProgressBar(0);
            progressModal.show();

            // 发送请求
            const response = await fetch('/api/fetch-hot-videos', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    page: parseInt(page),
                    page_size: parseInt(page_size),
                    date_window: parseInt(date_window)
                })
            });

            if (!response.ok) {
                throw new Error(`请求错误: ${response.status}`);
            }

            const data = await response.json();
            connectWebSocket(data.client_id);
            addProgressMessage('info', data.message);

        } catch (error) {
            console.error('拉取热门视频失败:', error);
            addProgressMessage('error', `拉取失败: ${error.message}`);
        }
    }

    // 下载单个视频
    async function downloadVideo(videoId) {
        try {
            // 显示进度弹窗
            document.getElementById('progressMessages').innerHTML = '';
            updateProgressBar(0);
            progressModal.show();

            // 发送下载请求
            const response = await fetch(`/api/hot-videos/${videoId}/download`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            });

            if (!response.ok) {
                throw new Error(`请求错误: ${response.status}`);
            }

            const data = await response.json();

            // 如果视频已下载，显示消息并关闭进度弹窗
            if (data.already_downloaded) {
                addProgressMessage('info', data.message);
                setTimeout(() => {
                    progressModal.hide();

                    // 可选：直接跳转到视频播放页面
                    // window.location.href = `/hot-videos/${videoId}/play`;
                }, 2000);
                return;
            }

            connectWebSocket(data.client_id);
            addProgressMessage('info', data.message);

        } catch (error) {
            console.error('下载视频失败:', error);
            addProgressMessage('error', `下载失败: ${error.message}`);
        }
    }

    // 获取手动下载链接
    async function getManualDownloadLinks(videoId) {
        try {
            // 显示下载链接弹窗
            document.getElementById('downloadLinksContainer').innerHTML = `
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
        `;
            manualDownloadModal.show();

            // 获取下载链接
            const response = await fetch(`/api/hot-videos/${videoId}/download-urls`);

            if (!response.ok) {
                throw new Error(`请求错误: ${response.status}`);
            }

            const data = await response.json();

            // 显示下载链接
            let linksHtml = `<h6>${data.title}</h6><div class="list-group">`;

            if (data.urls && data.urls.length > 0) {
                // 只显示前3个链接
                const displayUrls = data.urls.slice(0, 3);

                for (let i = 0; i < displayUrls.length; i++) {
                    linksHtml += `
                    <a href="${displayUrls[i]}" class="list-group-item list-group-item-action" target="_blank">
                        下载链接 ${i + 1} (优先级: ${i === 0 ? '高' : i === 1 ? '中' : '低'})
                    </a>
                `;
                }

                linksHtml += `</div>
                <div class="mt-3 alert alert-info">
                    <small>提示: 如果第一个链接无法下载，请尝试后面的链接。链接可能会在短时间内失效，请及时下载。</small>
                </div>`;
            } else {
                linksHtml = `<div class="alert alert-warning">未找到可用的下载链接</div>`;
            }

            document.getElementById('downloadLinksContainer').innerHTML = linksHtml;

        } catch (error) {
            console.error('获取下载链接失败:', error);
            document.getElementById('downloadLinksContainer').innerHTML = `
            <div class="alert alert-danger">获取下载链接失败: ${error.message}</div>
        `;
        }
    }

    // 删除视频
    async function deleteVideo(videoId) {
        if (!confirm('确定要删除这个视频吗？此操作不可恢复。')) {
            return;
        }

        try {
            const response = await fetch(`/api/hot-videos/${videoId}`, {
                method: 'DELETE'
            });

            if (!response.ok) {
                throw new Error(`请求错误: ${response.status}`);
            }

            // 刷新页面以更新UI
            location.reload();

        } catch (error) {
            console.error('删除失败:', error);
            alert(`删除失败: ${error.message}`);
        }
    }

    // 切换选中状态
    async function toggleSelect(videoId) {
        try {
            // 发送请求修改选中状态
            const response = await fetch(`/api/hot-videos/${videoId}/select`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error(`请求错误: ${response.status}`);
            }

            const data = await response.json();

            // 更新本地状态
            if (data.is_selected) {
                selectedVideos.add(videoId);
                document.getElementById(`video-card-${videoId}`).classList.add('border-primary');
            } else {
                selectedVideos.delete(videoId);
                document.getElementById(`video-card-${videoId}`).classList.remove('border-primary');
            }

            // 更新UI
            updateSelectedUI();

        } catch (error) {
            console.error('更新选中状态失败:', error);
            alert(`操作失败: ${error.message}`);
        }
    }

    // 全选/取消全选
    async function toggleSelectAll() {
        const videoIds = Array.from(document.querySelectorAll('.form-check-input')).map(checkbox => {
            return parseInt(checkbox.id.replace('select-', ''));
        });

        if (videoIds.length === 0) {
            return;
        }

        const newSelectState = !allSelected;

        try {
            // 发送批量选中/取消选中请求
            const response = await fetch('/api/hot-videos/batch-select', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    video_ids: videoIds,
                    select: newSelectState
                })
            });

            if (!response.ok) {
                throw new Error(`请求错误: ${response.status}`);
            }

            // 更新本地状态
            allSelected = newSelectState;

            if (newSelectState) {
                // 全选
                videoIds.forEach(id => {
                    selectedVideos.add(id);
                    const checkbox = document.getElementById(`select-${id}`);
                    if (checkbox) checkbox.checked = true;
                    const card = document.getElementById(`video-card-${id}`);
                    if (card) card.classList.add('border-primary');
                });
            } else {
                // 取消全选
                selectedVideos.clear();
                document.querySelectorAll('.form-check-input').forEach(checkbox => {
                    checkbox.checked = false;
                });
                document.querySelectorAll('.card').forEach(card => {
                    card.classList.remove('border-primary');
                });
            }

            // 更新UI
            updateSelectedUI();

        } catch (error) {
            console.error('批量操作失败:', error);
            alert(`操作失败: ${error.message}`);
        }
    }

    // 更新选中视频的UI显示
    function updateSelectedUI() {
        const selectAllBtn = document.getElementById('selectAllBtn');
        const unselectAllBtn = document.getElementById('unselectAllBtn');
        const selectedCountBadge = document.getElementById('selectedCount');
        const batchActions = document.getElementById('batchActions');

        // 更新计数
        selectedCountBadge.textContent = `已选择: ${selectedVideos.size}`;

        if (selectedVideos.size > 0) {
            selectedCountBadge.classList.remove('d-none');
            batchActions.classList.remove('d-none');
        } else {
            selectedCountBadge.classList.add('d-none');
            batchActions.classList.add('d-none');
        }

        // 更新全选/取消全选按钮
        if (allSelected) {
            selectAllBtn.classList.add('d-none');
            unselectAllBtn.classList.remove('d-none');
        } else {
            selectAllBtn.classList.remove('d-none');
            unselectAllBtn.classList.add('d-none');
        }
    }

    // 批量下载
    async function batchDownload() {
        if (selectedVideos.size === 0) {
            alert('请先选择要下载的视频');
            return;
        }

        if (!confirm(`确定要下载已选中的 ${selectedVideos.size} 个视频吗？`)) {
            return;
        }

        try {
            // 显示进度弹窗
            document.getElementById('progressMessages').innerHTML = '';
            updateProgressBar(0);
            progressModal.show();

            // 发送批量下载请求
            const response = await fetch('/api/hot-videos/batch-download', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(Array.from(selectedVideos))
            });

            if (!response.ok) {
                throw new Error(`请求错误: ${response.status}`);
            }

            const data = await response.json();

            // 如果全部都已下载完成，显示消息并关闭进度弹窗
            if (data.already_downloaded && data.already_downloaded === selectedVideos.size) {
                addProgressMessage('info', data.message);
                setTimeout(() => {
                    progressModal.hide();
                }, 2000);
                return;
            }

            connectWebSocket(data.client_id);
            addProgressMessage('info', data.message);

        } catch (error) {
            console.error('批量下载失败:', error);
            addProgressMessage('error', `批量下载失败: ${error.message}`);
        }
    }

    // 批量删除
    async function batchDelete() {
        if (selectedVideos.size === 0) {
            alert('请先选择要删除的视频');
            return;
        }

        if (!confirm(`确定要删除已选中的 ${selectedVideos.size} 个视频吗？此操作不可恢复。`)) {
            return;
        }

        try {
            // 发送批量删除请求
            const response = await fetch('/api/hot-videos/batch', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(Array.from(selectedVideos))
            });

            if (!response.ok) {
                throw new Error(`请求错误: ${response.status}`);
            }

            const data = await response.json();
            alert(data.message);

            // 刷新页面以更新UI
            location.reload();

        } catch (error) {
            console.error('批量删除失败:', error);
            alert(`批量删除失败: ${error.message}`);
        }
    }

    // 更改每页显示数量
    function changePageSize() {
        const urlParams = new URLSearchParams(window.location.search);
        const newPerPage = document.getElementById('per-page-filter').value;

        urlParams.set('per_page', newPerPage);
        // 重置页码
        urlParams.set('page', '1');

        // 跳转到新的URL
        window.location.href = `?${urlParams.toString()}`;
    }

    // 更改排序方式
    function changeSort() {
        const urlParams = new URLSearchParams(window.location.search);
        const newSortBy = document.getElementById('sort-by-filter').value;

        urlParams.set('sort_by', newSortBy);
        // 重置页码
        urlParams.set('page', '1');

        // 跳转到新的URL
        window.location.href = `?${urlParams.toString()}`;
    }

    // 切换排序顺序
    function toggleSortOrder() {
        const urlParams = new URLSearchParams(window.location.search);
        const currentOrder = urlParams.get('sort_order') || 'asc';

        // 切换排序顺序
        const newOrder = currentOrder === 'asc' ? 'desc' : 'asc';
        urlParams.set('sort_order', newOrder);

        // 重置页码
        urlParams.set('page', '1');

        // 跳转到新的URL
        window.location.href = `?${urlParams.toString()}`;
    }

    // 应用日期筛选
    function applyDateFilter() {
        const urlParams = new URLSearchParams(window.location.search);
        const startDate = document.getElementById('start_date').value;
        const endDate = document.getElementById('end_date').value;

        // 设置日期参数
        if (startDate) {
            urlParams.set('start_date', startDate);
        } else {
            urlParams.delete('start_date');
        }

        if (endDate) {
            urlParams.set('end_date', endDate);
        } else {
            urlParams.delete('end_date');
        }

        // 重置页码
        urlParams.set('page', '1');

        // 跳转到新的URL
        window.location.href = `?${urlParams.toString()}`;
    }

    // 清除日期筛选
    function clearDateFilter() {
        const urlParams = new URLSearchParams(window.location.search);

        // 删除日期参数
        urlParams.delete('start_date');
        urlParams.delete('end_date');

        // 重置页码
        urlParams.set('page', '1');

        // 跳转到新的URL
        window.location.href = `?${urlParams.toString()}`;
    }

    // 快捷设置日期筛选
    function setDateFilter(preset) {
        const now = new Date();
        let startDate = new Date();
        let endDate = new Date();

        switch(preset) {
            case 'today':
                // 今天的日期范围
                startDate = now;
                endDate = now;
                break;
            case 'yesterday':
                // 昨天的日期范围
                startDate.setDate(now.getDate() - 1);
                endDate.setDate(now.getDate() - 1);
                break;
            case 'this_week':
                // 本周的日期范围（周一到今天）
                startDate.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1)); // 将日期设为本周一
                break;
            case 'last_week':
                // 上周的日期范围（上周一到上周日）
                startDate.setDate(now.getDate() - now.getDay() - 6 + (now.getDay() === 0 ? -7 : 0)); // 上周一
                endDate.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -7 : 0)); // 上周日
                break;
            case 'this_month':
                // 本月的日期范围（本月1日到今天）
                startDate.setDate(1); // 本月1日
                break;
        }

        // 格式化日期为YYYY-MM-DD格式
        document.getElementById('start_date').value = formatDate(startDate);
        document.getElementById('end_date').value = formatDate(endDate);

        // 立即应用筛选
        applyDateFilter();
    }

    // 日期格式化辅助函数
    function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }
</script>
{% endblock %}